package com.wxj.bank.storage.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wxj.bank.module.constant.Constants;
import com.wxj.bank.module.page.PageBean;
import com.wxj.bank.module.utils.UUIDUtils;
import com.wxj.bank.storage.dao.ProductMapper;
import com.wxj.bank.storage.model.Product;
import com.wxj.bank.storage.model.ProductExample;
import com.wxj.bank.storage.service.IProductService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author shengtao
 * @Description: 商品服务类
 * @date 2019/02/19 16:39
 */
@Service
public class ProductServiceImpl implements IProductService{

    @Autowired
    private ProductMapper productMapper;


    @Override
    public Product save(Product product) {
        product.setId(UUIDUtils.genUUID());
        productMapper.insert(product);
        return product;
    }

    @Override
    public void save(List<Product> products) {
        products.stream().map(product -> {product.setId(UUIDUtils.genUUID());return product;}).collect(toList());
        productMapper.batchInsert(products);
    }

    @Override
    public void remove(String id) {
        productMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Product update(Product product) {
        productMapper.updateByPrimaryKey(product);
        return product;
    }

    @Override
    public Product find(String id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Product> find(Product product) {
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(product.getId())){
            criteria.andIdEqualTo(product.getId());
        }
        if(StringUtils.isNotBlank(product.getName())){
            criteria.andNameLike(product.getName()+ Constants.SYMBOL_PERCENT);
        }
        return productMapper.selectByExample(example);
    }

    @Override
    public PageBean<Product> find(Product product, PageBean<Product> page) {
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(product.getId())){
            criteria.andIdEqualTo(product.getId());
        }
        if(StringUtils.isNotBlank(product.getName())){
            criteria.andNameLike(product.getName()+ Constants.SYMBOL_PERCENT);
        }
        Page<Product> pages = PageHelper.startPage(page.getCurrentPage(),page.getPageSize());
        productMapper.selectByExample(example);
        return new PageBean<>(pages);
    }
}
